#!/bin/sh
runnable startupvideo || exit 0

case "$1" in
  start)
    (
      if is-tv-box; then
        echo "Starting startupvideo."
        rm -f /tmp/svpipe
        mknod /tmp/svpipe p

        # sv monitor process
        (
          # Sleep and then write svpipe to terminate startupvideo, if we haven't
          # been killed.
          sleep 7200
          echo "Startupvideo reaches timeout. Finishing startupvideo."

          # Kill startupvideo
          pid_startupvideo=$(pgrep -f "startupvideo /tmp/svpipe")
          if [ "$pid_startupvideo" -gt 1 ]; then
            kill -TERM "$pid_startupvideo"
          fi
        ) &
        alarm=$!

        (
          wait-until-created /tmp/mcnmp_ready
          startupvideo /tmp/svpipe \
             /usr/sv/fiber-logo-animation.ts 2 0 256 257 0 \
             /usr/sv/connecting.ts 2 0 256 0 1

          # in case sv crashes early, make sure ntp is synced
          wait-until-created /tmp/time.synced

          if [ -d /proc/"$alarm" ] && [ "$alarm" -gt 1 ]; then
            # If the alarm process is still alive, sv exits within timeout
            # (normal case). We need to clean it up.
            kill -TERM "$alarm"
          fi
          echo : >/tmp/startupvideo.done
       ) &

       (
         wait-until-created /tmp/time.synced
         echo y >/tmp/svpipe
       ) &
     else
       (
         wait-until-created /tmp/time.synced
         echo : >/tmp/startupvideo.done
       ) &
     fi
    ) 2>&1 | logos startupvideo &
    ;;
  stop)
    pkillwait -x startupvideo
    rm -f /tmp/svpipe
    ;;
  restart)
    $0 stop; $0 start
    ;;
  *)
  echo "Usage: $0 {start|stop|restart}"
  exit 1
esac
